package com.sky.aspect;

import com.sky.anno.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.descriptor.web.MessageDestination;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class AutoFillAspect {
    @Pointcut("@annotation(com.sky.anno.AutoFill)")
    public void point(){};

    @Before("point()")
    public void b(JoinPoint joinPoint){
        log.info("方法字段自动填充----------");
        MethodSignature signature =(MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        Object[] args = joinPoint.getArgs();

        if( args == null || args.length != 1){
            return;
        }
        Object arg = args[0];
        try {
            if(annotation.value() == OperationType.INSERT){
                Method ct = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method ut = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method cu = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method uu = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                ct.invoke(arg,LocalDateTime.now());
                ut.invoke(arg,LocalDateTime.now());
                cu.invoke(arg, BaseContext.getCurrentId());
                uu.invoke(arg,BaseContext.getCurrentId());
            } else if (annotation.value() == OperationType.UPDATE) {
                Method ut = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method uu = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                ut.invoke(arg,LocalDateTime.now());
                uu.invoke(arg,BaseContext.getCurrentId());
            }
        }catch (Exception e){

            log.error("切入点异常：==",e.getMessage());
            throw new RuntimeException();
        }


    }
}
